package com.xw.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import com.xw.convert.dataConvert;


//import android.os.NetworkOnMainThreadException;
import android.accounts.NetworkErrorException;
import android.util.Log;

public class Jsocket {

	// TCP Socket
	public Socket socket;
	private InetAddress serverAddr;
	
	
	private String m_ip = "116.255.194.227";
	int m_port = 8800;
	
//	
//	private String m_ip = "192.168.1.8";
//	int m_port = 8900;

	public Jsocket() {
		if (serverAddr == null) {

			try {
				serverAddr = InetAddress.getByName(m_ip);

			} catch (UnknownHostException e) {
				e.printStackTrace();

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 连接服务器

	public Socket SocketConnect() {

		try {
			
			socket = new Socket();
			socket.connect(new InetSocketAddress(serverAddr, m_port), 5000);
			socket.setSoTimeout(10000);// 不要让其阻塞

		} 
		catch(IOException e) {

			SocketClose();
		

		} catch (Exception e) {
			SocketClose();
		}

		return socket;

	}

	// 发送包
	public void SendPack(int cmd, byte[] sendBytes) throws IOException,
			Exception {

		socket.setSoTimeout(5000);
		OutputStream outStrm = socket.getOutputStream();
		outStrm.write(sendBytes);
		String sendStr = dataConvert.byteArrToHexStr(sendBytes);

		if (cmd == 5000) // login־
		{
			Log.i("wuliu", "login Send:" + sendStr);
		} else if (cmd == 9955) {
			Log.i("wuliu", "post location:" + sendStr);
		}

	}

	// 接收包
	public byte[] RecvPack(int cmd) {
		byte[] recvBuf = null;

		try {

			socket.setSoTimeout(5000);
			InputStream inStrm = socket.getInputStream();

			int size = inStrm.read();

			if (size > 0) {
				recvBuf = new byte[size];
				int len = inStrm.read(recvBuf);
				String recvStr = dataConvert.byteArrToHexStr(recvBuf);
				if (cmd == 5000)// login־
				{

					Log.i("wuliu", "login recv:" + recvStr);
				} else if (cmd == 9955) {
					Log.i("wuliu", "gps return:" + recvStr);

				}
			}

		} catch (IOException e) {

			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}

		return recvBuf;
	}

	public void SocketClose() {
		if (socket != null) {
			try {
			
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			socket = null;
		}

	}

}
